<template>
  <div
    :title="view === 'create'? '新增': '编辑'"
    :visible="true"
    :before-close="closeDialog"
    >
    <el-form :model="formData" label-width="120px" ref="ruleForm" class="diafrom" :rules="rules">
      <el-form-item label="商品名称" prop="productName">
        <el-input v-model.trim="formData.productName" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="销售价格" prop="originalPrice">
        <el-input v-model.trim="formData.originalPrice" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="市场价" prop="bazaarPrice">
        <el-input v-model.trim="formData.bazaarPrice" auto-complete="off"></el-input>
      </el-form-item>
			<el-form-item label="售卖数量" prop="number">
        <el-input v-model.trim="formData.number" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="商品类别" prop="category" required>
				<el-cascader
					:options="CategoryList"
					:props="cascaderConfig"
					v-model="formData.category"
					:change-on-select="ifSelect">
				</el-cascader>
      </el-form-item>
			<el-form-item label="规格添加" prop="txt">
        <el-button type="info" @click="specOper">管理规格</el-button>
      </el-form-item>
			<el-form-item label="选择规格组合">
				<el-button type="info" @click="specVisible">选择规格组合</el-button>
			</el-form-item>	
			<el-form-item label="规格组合列表">
				<el-table
				:data="formData.specList"
				style="width: 100%">
				<el-table-column
					prop="specId"
					label="规格组合id"
					>
				</el-table-column>
				<el-table-column
				prop="specName"
					label="规格组合名称"
					>
				</el-table-column>
					<el-table-column
					label="规格价格"
					>
					<template slot-scope="scope">
					<el-input v-model="scope.row.specPrice" auto-complete="off"></el-input>
				</template>
				</el-table-column>
				<el-table-column label="操作" >
						<template slot-scope="scope">
						<el-button
							size="mini"
							type="danger"
							@click="specDelete(scope.$index, scope.row, formData.specList)">删除</el-button>
						</template>
					</el-table-column>
			</el-table>
			</el-form-item>		
      <el-form-item label="兑换规则" prop="productDetails">
         <tinymce v-model.trim="formData.productDetails"></tinymce>
      </el-form-item>
      <el-form-item label="序号" prop="serialNumber">
        <el-input v-model.trim="formData.serialNumber" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="商品类型" prop="productType" v-if=" view === 'create'">
        <el-select v-model.trim="formData.productType">
          <!-- <el-option v-for="(item, index) in ['实物', '彩票','券/虚拟','优惠券']" :value="String(index+1)" :label="item" :key="index"></el-option> -->
					<el-option label="实物" value="1"></el-option>
          <el-option label="彩票" value="2"></el-option>
					<el-option label="优惠券" value="4"></el-option>
				</el-select>
      </el-form-item>
			<!-- <el-form-item label="销售价格" style="display:none" prop="salePrice">
        <el-input v-model.trim="formData.salePrice" auto-complete="off"></el-input>
      </el-form-item> -->
      <el-form-item label="运费" prop="freight">
        <el-input v-model.trim="formData.freight" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="支付方式" prop="payMethod">
        <el-select v-model.trim="formData.payMethod">
          <el-option v-for="(item, index) in ['RMB']" :value="String(index+1)" :label="item" :key="index"></el-option>
        </el-select>
      </el-form-item>
			<el-form-item label="选择优惠券" prop="couponNo" v-if="formData.productType === '4'" required>
        <el-select v-model.trim="formData.couponNo" @change="onSelectedCoupon">
              <el-option 
              	v-for="item in couponList"
      					:key="item.couponNo"
      					:label="item.couponName"
      					:value="item.couponNo"
      				></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="封面图片" prop="picUrl">
      	<div class="editImg" v-if="imgShow === 'edit' && formData.picUrl != ''">
      		<img :src="imgSrc(formData.picUrl)" />
      	</div>
        <el-upload
			   	ref="upload"
				  :action="baseUrl()"
				  class="upload-demo"
				  list-type="picture-card"
				  accept="image/jpeg,image/gif,image/png,image/bmp"
				  :on-preview="handlePictureCardPreview"
				  :on-remove="handleRemove"
				  :on-change="handleChangeImg"
				  :auto-upload = "false"
					:before-remove="beforeRemove"
          :on-exceed="handleExceed"
					:limit="1"
					:file-list="fileList"
				  :drag="false"
				  >
				  <i class="el-icon-plus"></i>
				   <div slot="tip" class="el-upload__tip">建议尺寸：450*380</div>
				</el-upload>
				<el-dialog :visible.sync="dialogVisible" size="tiny">
				  <img width="100%" :src="dialogImageUrl" alt="">
				</el-dialog>
      </el-form-item>
      <el-form-item label="有效开始时间" v-if="formData.productType === '3'" prop="startDate">
         <div class="block">
				    <el-date-picker
				      v-model="formData.startDate"
				      format="yyyy-MM-dd HH:mm:ss"
				      value-format="yyyy-MM-dd HH:mm:ss"
				      type="datetime"
				      :picker-options="pickerBeginDateBefore"
				      placeholder="选择日期时间">
				    </el-date-picker>
				  </div>
      </el-form-item>
      <el-form-item label="有效期结束时间" v-if="formData.productType === '3'" prop="endDate">
         <div class="block">
				    <el-date-picker
				      v-model="formData.endDate"
				      format="yyyy-MM-dd HH:mm:ss"
				      value-format="yyyy-MM-dd HH:mm:ss"
				      type="datetime"
				      :picker-options="pickerBeginDateAfter"
				      placeholder="选择日期时间">
				    </el-date-picker>
				  </div>
      </el-form-item>
			<el-form-item label="有效开始时间" v-if="formData.productType === '4'" prop="startDate">
        <el-input v-model.trim="formData.startDate" auto-complete="off" readonly="readonly" style="width:193px"></el-input>
      </el-form-item>
			<el-form-item label="有效结束时间" v-if="formData.productType === '4'" prop="endDate">
        <el-input v-model.trim="formData.endDate" auto-complete="off"  readonly="readonly" style="width:193px"></el-input>
      </el-form-item>
      <!-- <el-form-item label="结算金额" style="display:none" prop="closingAmt">
        <el-input v-model.trim="formData.closingAmt" auto-complete="off"></el-input>
      </el-form-item> -->
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="info" @click="submit('ruleForm')" :disabled="Subabled">确 定</el-button>
    </div>
		<index-spec
		ref="index-spec"
		@close="editFinish"
		v-if="specview ==='spec'"/>
		<edit-spec
		ref="edit-spec"
		@close="editFinish"
		:view="showview"
		v-if="showview ==='create' || showview ==='edit'"/>
		<edit-comb
		ref="edit-comb"
		@close="editFinish"
		@succback="specFinish"
		:view="combview"
		v-if="combview ==='open'"/>
  </div>
	
</template>

<script>
import { queryAllCategory,queryCouponinfo } from "@/services/product";
import { queryspec,query,create,edit,del } from "@/services/spec";
import { oneFile} from "@/services/getFromData";
import { RequestError } from "@/services/errors";
import { mapActions } from "vuex";
import {deepClone} from '@/utilities/object'
import IndexSpec from './proSpec/indexSpec'
import EditSpec from './proSpec/editSpec'
import EditComb from './proSpec/combedit'
import Tinymce from "@/components/Tinymce";
var vailMoney = (rule, value, callback) => {
	if(value != ''){
		var MoneyRegex = /^(0|([1-9]\d{0,8}))(\.\d{1,2})?$/;
			if (!MoneyRegex.test(value)) {
				callback(new Error('数字格式不正确,最多可输入两位小数'))
			} else {
				callback();
	    }
	}
};
var vailNumber = (rule, value, callback) => {
	var NumberyRegex = /^[0-9]*$/;
	if (!NumberyRegex.test(value)) {
	    callback(new Error('格式不正确,只能输入数字'))
	    } else {
	        callback();
	    }
};

export default {
  name: "edit-role",
	components: {Tinymce,EditSpec,EditComb,IndexSpec},
  data () {
    return {
			showview: '',
			combview:'',
			specview:'',
			currentPage: 1,
      pageSize: 10,
			loading: false,
			tableData: [],
			fileList:[],
			file:{},
			CategoryList:[],
			ifSelect:true,
			cascaderConfig: {
				label: 'categoryName',
				value: 'categoryNo',
				children: 'secondLevel'
			},
			couponList:[],
      imgShow:"",
			Subabled:false,
      formData: {
				id:"",
				mchtId:"",
        productName: "",
				originalPrice: "",
				number:"",
        bazaarPrice:"",
        category: [],
        productDetails:"",
        serialNumber:"",
        productType:"",
        salePrice:"",
        freight:"",
        payMethod:"",
				couponNo:"",
        startDate:"",
        endDate:"",
				closingAmt:"",
				specList:[
        ]
      },
			tree:[],
      dialogImageUrl: '',
      dialogVisible: false,
      dialogFormVisible: false,
      pickerBeginDateBefore:{
            disabledDate: (time) => {
                let beginDateVal = this.formData.endDate;
                if (beginDateVal) {
                    return time.getTime() > beginDateVal;
                }
            }
			},
			pickerBeginDateAfter:{
					disabledDate: (time) => {
							let beginDateVal = this.formData.startDate;
							if (beginDateVal) {
									return time.getTime() < beginDateVal;
							}
					}
			},
      rules: {
        productName: [{ required: true, message: "请输入商品名称", trigger: "blur" },
         { min: 1, max: 50, message: '长度在 50个字符以内', trigger: 'blur' }],
         //两位有效数字
        originalPrice: [{ required: true, message: "请输入商品原价", trigger: 'blur'},
        { min: 1, max: 12, message: '长度在 12个字符以内', trigger: 'blur' },
        { validator: vailMoney, trigger: 'blur'}],
        bazaarPrice: [{ required: true, message: "请输入市场价", trigger: 'blur'},
        { min: 1, max: 12, message: '长度在 12个字符以内', trigger: 'blur' },
        { validator: vailMoney, trigger: 'blur'}],
        productDetails: [{ required: false, message: "请输入兑换规则", trigger: "blur" }],
        serialNumber: [{ required: true, message: "请输入序号", trigger: "blur" },
        { min: 1, max: 11, message: '长度在 11个字符以内', trigger: 'blur' },
				 { validator: vailNumber, trigger: 'blur'}],
				 number: [{ required: true, message: "请输入数量", trigger: "blur" },
        { min: 1, max: 11, message: '长度在 11个字符以内', trigger: 'blur' },
   			{ validator: vailNumber, trigger: 'blur'}],
				productType: [{ required: true, message: "请选择商品类型", trigger: 'change' }],
				category: [{ required: true, message: "请选择商品类别", trigger: 'change' }],
        //两位有效数字
        // salePrice: [{ required: true, message: "请输入销售价格", trigger: "blur" },
        // { min: 1, max: 12, message: '长度在 12个字符以内', trigger: 'blur' },
        // { validator: vailMoney, trigger: 'blur'}],
        //两位有效数字
        freight: [{ required: true, message: "请输入运费", trigger: "blur" },
        { min: 1, max: 12, message: '长度在 12个字符以内', trigger: 'blur' },
        { validator: vailMoney, trigger: 'blur'}],
        payMethod: [{ required: true, message: "请选择支付方式", trigger: "change" }],
        // closingAmt: [{ required: false, message: "请输入结算金额", trigger: "blur" },
        // { min: 1, max: 12, message: '长度在 12个字符以内', trigger: 'blur' },
        // { validator: vailMoney, trigger: 'blur'}],
      }
    }
  },
  props: {
    view: {
      type: String,
      default: "create"
    }
  },
  methods: {
    ...mapActions(["setUserInfo"]),
    closeDialog() {
      this.$emit("close");
		},
		handleClose(done) {
				this.condialogVisible = false;
    },
    baseUrl(){
    	return "api/console/product/addInfo.do";
    },
    imgSrc(data){
      	return this.$store.state.imgUrl + data;
    },
    handleRemove(file, fileList) {
			// console.log(file, fileList);
			this.file = "";
 	  },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
			return this.$confirm(`确定移除 ${ file.name }？`);
		},
		handleExceed(files, fileList) {
			this.$message.warning(`当前限制只能导入 1 个文件`);
		},
    handleChangeImg(file, fileList){
				this.file = file.raw;
				this.imgShow = ""
				this.regImage(file);
        this.regMemory(file);
		},
		regMemory(file){
			const isLt10M = file.size / 1024 / 1024 < 2;
			if (!isLt10M) {
				this.$refs.upload.clearFiles();
				this.$message.error('上传图片大小不能超过 2MB!');
				this.file = ""
			}
		},
		regImage(file){
			var path = file.raw.name;  //得到的是现在文件的路径
			var Suffix = path.substr(path.lastIndexOf(".")).toUpperCase();//得到的是后缀名,且转换为大写
			// console.log(Suffix)
			if(Suffix != ".JPG" && Suffix !=".PNG" && Suffix !=".JPEG"){
				  this.$refs.upload.clearFiles();
					this.$message.error('上传图片只能是 JPG/PNG 格式！');
					this.file = ""
			}
		},
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
		},
		editFinish (needRefresh) {
				this.specview =''
				this.showview = ''
				this.combview = ''
		},
		specFinish(params){
				// this.specfromData = params;
				this.formData.specList.push(params)
		},
		onSelectedCoupon(data){
			for(let item of this.couponList) {  
					if(item.couponNo == data){
						this.formData.startDate = item.validatyBegin
            this.formData.endDate = item.validatyEnd
					}
			}
		},
		// 查询商品类别
    async loadCategory () {
        try {
					let data = await queryAllCategory();
					this.CategoryList = data;
        } catch (e) {
          if (e instanceof RequestError) {
            this.$alert(e.message, '提示', {
              type: 'error',
              confirmButtonText: '确定'
            })
          } else {
            throw e
          }
        }
        this.loading = false
		},
		// 查询优惠券类别
		async loadCoupon () {
        try {
          let data = await queryCouponinfo()
          this.couponList = data.data
        } catch (e) {
          if (e instanceof RequestError) {
            this.$alert(e.message, '提示', {
              type: 'error',
              confirmButtonText: '确定'
            })
          } else {
            throw e
          }
        }
        this.loading = false
		},
		// 规格组合选择弹窗的显示
		async specVisible () {
        this.combview = 'open'
        await this.$nextTick()
        this.$refs['edit-comb'].loadSelect(this.formData.mchtId)
		},
		// 规格管理各项操作与接口
		async specOper(){
			this.specview = 'spec'
			await this.$nextTick()
			this.$refs['index-spec'].queryTree(this.formData.mchtId);
			this.$refs['index-spec'].loadData(this.currentPage,this.formData.mchtId);
			this.$refs['index-spec'].formData.mchtId = this.formData.mchtId;
		},
		// 规格组合表格删除的操作
		specDelete(index, data, rows){
			this.$confirm(`此操作将删除${data.specName}, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
						rows.splice(index, 1)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
		},
    formatDateTime (date) {  
		  var y = date.getFullYear();  
		  var m = date.getMonth() + 1;  
		  m = m < 10 ? ('0' + m) : m;  
		  var d = date.getDate();  
		  d = d < 10 ? ('0' + d) : d;  
		  var h = date.getHours();  
		  h=h < 10 ? ('0' + h) : h;  
		  var minute = date.getMinutes();
		  minute = minute < 10 ? ('0' + minute) : minute;  
		  var second=date.getSeconds();  
		  second=second < 10 ? ('0' + second) : second;  
		  return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;  
		},
    submit(formName) {
			this.Subabled = true;
			this.butTimeOut();
      this.$refs[formName].validate(async valid => {
        if (valid) {
          try {
            if (this.view === "create") {
							var sref = this;
            	//把图片的信息和参数放进请求头里
							let reg = RegExp(/T/);
							if(JSON.stringify(this.formData.startDate).match(reg)){
								this.formData.startDate = this.formatDateTime(this.formData.startDate);
							}
							if(JSON.stringify(this.formData.endDate).match(reg)){
								this.formData.endDate = this.formatDateTime(this.formData.endDate);
							}
							var categoryLength = this.formData.category.length;
            	let code = await oneFile({
								mchtId: this.formData.mchtId,
				        productName: this.formData.productName,
								originalPrice: this.formData.originalPrice,
								number:this.formData.number,
				        bazaarPrice:this.formData.bazaarPrice,
				        categoryNo: this.formData.category[categoryLength-1],
				        productDetails:this.formData.productDetails,
				        serialNumber:this.formData.serialNumber,
				        productType:this.formData.productType,
				        salePrice:this.formData.originalPrice,
				        freight:this.formData.freight,
				        payMethod:this.formData.payMethod,
				        startDate:this.formData.startDate,
				        endDate:this.formData.endDate,
								closingAmt:this.formData.originalPrice,
								specList:this.formData.specList,
								couponNo:this.formData.couponNo
				      },"/ecshop/console/product/addInfo.do","coverPicImg",sref.file).then(
								function(data){
									sref.$message({
										showClose: true,
										message: data,
										type: "success"
									});
									sref.$emit("close", true);
								}, 
								function(reason, data){
									sref.$message({
										showClose: true,
										message: reason,
										type: "error"
									});
								});
            } 
            else {
							var sref = this;
							let reg = RegExp(/T/);
							if(JSON.stringify(this.formData.startDate).match(reg)){
								this.formData.startDate = this.formatDateTime(this.formData.startDate);
							}
							if(JSON.stringify(this.formData.endDate).match(reg)){
								this.formData.endDate = this.formatDateTime(this.formData.endDate);
							}
							var categoryLength = this.formData.category.length;
              let code = await oneFile({
								id: this.formData.id,
								mchtId: this.formData.mchtId,
				        productName: this.formData.productName,
								originalPrice: this.formData.originalPrice,
								number:this.formData.number,
				        bazaarPrice:this.formData.bazaarPrice,
				        categoryNo: this.formData.category[categoryLength-1],
				        productDetails:this.formData.productDetails,
				        serialNumber:this.formData.serialNumber,
				        productType:this.formData.productType,
				        salePrice:this.formData.originalPrice,
				        freight:this.formData.freight,
				        payMethod:this.formData.payMethod,
				        startDate:this.formData.startDate,
				        endDate:this.formData.endDate,
								closingAmt:this.formData.originalPrice,
								specList:this.formData.specList,
								couponNo:this.formData.couponNo
				      },"/ecshop/console/product/updateInfo.do","coverPicImg",sref.file).then(
								function(data){
									sref.$message({
										showClose: true,
										message: data,
										type: "success"
									});
									sref.$emit("close", true);
								}, 
								function(reason, data){
									sref.$message({
										showClose: true,
										message: reason,
										type: "error"
									});
								});
            }
            this.dialogFormVisible = false;
          } catch (e) {
            if (e instanceof RequestError) {
              this.$alert(e.message, "提示", {
                type: "error",
                confirmButtonText: "确定"
              });
            } else {
              throw e;
            }
          }
        } else {
          return;
        }
      });
		},
		butTimeOut(){
			var serf = this;
			setTimeout(function(){
				serf.Subabled = false;
			},1200)
		}
  },
	mounted() {},
	watch: {
		currentPage (newVal) {
			// console.log(newVal)
      this.loadData(newVal,this.formData.mchtId);
		}
	}
};
</script>
<style>
.diafrom{
	width: 100%;
	float: left;
}
.el-dialog{
   /* z-index: 99; */
	 width: 800px;
}
.editContent{
	width: 100%;
	overflow: hidden;
}
.left_content{
	width: 20%;
	float: left;
}
.editContent .right_content{
	width: 78%;
	float: left;
}
.el-select {
  width: 100%;
}
.editImg{
	  overflow: hidden;
    background-color: #fff;
    border: 1px solid #c0ccda;
    border-radius: 6px;
    box-sizing: border-box;
    width: 148px;
    height: 148px;
    margin: 0 8px 8px 0;
    display: inline-block;
    float: left;
}
.editImg img{
	width: 100%;
	height: 100%;
}
</style>
